package cn.tedu.csmall.cart.webapi.kafka;

import cn.tedu.csmall.commons.pojo.cart.entity.Cart;
import com.google.gson.Gson;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class Producer {

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    public static final String TOPIC_KEY = "myCart";

    int i = 1;

    @Scheduled(fixedRate = 10000)
    public void sendMessage() {
        Cart cart = new Cart();
        cart.setId(i++);
        cart.setCommodityCode("PC100");
        cart.setUserId("UU100");
        cart.setPrice(10 + RandomUtils.nextInt(90));
        cart.setCount(3 + RandomUtils.nextInt(9));

        Gson gson = new Gson();
        String json = gson.toJson(cart);
        System.out.println("要发送的json格式字符串为：" + json);
        kafkaTemplate.send(TOPIC_KEY, json);
    }
}
